from fastapi import APIRouter, Request, Depends, Form, HTTPException
from fastapi.responses import RedirectResponse, JSONResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
from sqlalchemy import desc
from models import Users, ApiCalls, ApiCallLogs, Orders, Kami
from database import get_db
from utils.captcha import verify_captcha
from utils.config import ConfigData
from passlib.context import CryptContext
import hashlib
from datetime import datetime
import uuid

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

router = APIRouter(tags=["用户模块"], prefix="/user")
templates = Jinja2Templates(directory="templates")


def verify_password(input_password: str, stored_hash: str) -> bool:
    """验证输入的密码是否与存储的哈希匹配"""
    return pwd_context.verify(input_password, stored_hash)  # ✅ 关键修复


def hash_password(pwd: str):
    return hashlib.sha256(pwd.encode()).hexdigest()


@router.get("/register")
def register_page(request: Request):
    return templates.TemplateResponse("register.html", {"request": request})


@router.post("/register")
def register(
        request: Request,
        username: str = Form(...),
        password: str = Form(...),
        captcha_input: str = Form(...),  # 新增验证码输入
        db: Session = Depends(get_db)
):
    # 先校验验证码
    if not verify_captcha(request, captcha_input):
        return JSONResponse({"code": 0, "msg": "验证码错误"})

    if db.query(Users).filter_by(username=username).first():
        return JSONResponse({"code": 0, "msg": "用户名已存在"})

    user = Users(username=username, password=pwd_context.hash(password))
    db.add(user)
    db.commit()
    return JSONResponse({"code": 1, "msg": "注册成功"})


@router.get("/login")
def login_page(request: Request):
    return templates.TemplateResponse("login.html", {"request": request})


@router.post("/login")
def login(request: Request, username: str = Form(...), password: str = Form(...), captcha_input: str = Form(...),
          db: Session = Depends(get_db)):
    # 先校验验证码
    if not verify_captcha(request, captcha_input):
        return JSONResponse({"code": 0, "msg": "验证码错误"})

    user = db.query(Users).filter_by(username=username).first()
    if not user:
        return JSONResponse({"code": 0, "msg": "用户名或密码错误1"})
        # return templates.TemplateResponse("login.html", {"request": request, "error": "用户名或密码错误"})

    # 3. 验证密码（关键！使用 passlib 的 verify 方法）
    if not pwd_context.verify(password, user.password):
        return JSONResponse({"code": 0, "msg": "用户名或密码错误2"})

    # 登录成功，保存 session
    request.session["user"] = {"user_id": user.user_id, "username": user.username, "is_admin": 0}
    request.session["user_id"] = user.user_id
    return JSONResponse({"code": 1, "msg": "登录成功"})

    # return RedirectResponse("/user/dashboard", status_code=302)


@router.get("/dashboard")
def dashboard(request: Request, db: Session = Depends(get_db)):
    user_id = request.session.get("user_id")
    if not user_id:
        return RedirectResponse("/user/login")

    user = db.query(Users).filter_by(user_id=user_id).first()
    if not user:
        return RedirectResponse("/user/login")

    # 今日日期
    today = datetime.now().date()

    # 查询今天的调用记录
    today_calls = (
        db.query(ApiCalls)
        .filter(ApiCalls.user_id == user_id, ApiCalls.call_date == today)
        .first()
    )

    used_calls = today_calls.call_count if today_calls else 0

    # 获取用户的每日调用限制(根据 user.user_type.value 定义不同的额度)
    user_configs = ConfigData.get_user_configs()
    daily_limit = user_configs[user.user_type.value]["daily_limit"]

    # 剩余次数 = 上限 - 已用
    remaining_calls = max(daily_limit - used_calls, 0)

    # 获取用户的分组
    user_type_label = user_configs[user.user_type.value]["label"]

    # 获取最近5条接口调用记录
    recent_logs = (
        db.query(ApiCallLogs)
        .filter(ApiCallLogs.user_id == user_id)
        .order_by(desc(ApiCallLogs.created_at))
        .limit(5)
        .all()
    )

    # 查询最近支付记录
    buy_records = (
        db.query(Orders)
        .filter(Orders.user_id == user_id, Orders.status == "paid")
        .order_by(Orders.paid_at.desc())
        .limit(3)
        .all()
    )

    return templates.TemplateResponse(
        "dashboard.html",
        {
            "request": request,
            "user": user,
            "used_calls": used_calls,
            "remaining_calls": remaining_calls,
            "daily_limit": daily_limit,
            "user_type_label": user_type_label,
            "recent_logs": recent_logs,
            "buy_records": buy_records,
        }
    )


@router.get("/getapi")
def get_api_page(request: Request, db: Session = Depends(get_db)):
    """
    GET 页面渲染
    """
    user_id = request.session.get("user_id")
    user = None
    if user_id:
        user = db.query(Users).filter(Users.user_id == user_id).first()
    return templates.TemplateResponse(
        "getapi.html",
        {"request": request, "user": user, "active_page": "getapi"}
    )


@router.post("/getapi")
def apply_api(request: Request, db: Session = Depends(get_db)):
    """
    用户点击申请接口按钮时调用
    """
    user_id = request.session.get("user_id")
    if not user_id:
        return JSONResponse({"code": 0, "msg": "未登录"})

    user = db.query(Users).filter(Users.user_id == user_id).first()

    if not user:
        return JSONResponse({"code": 0, "msg": "用户不存在"})

    if user.client_secret:
        return JSONResponse({"code": 0, "msg": "接口已开通"})

    # 生成 client_secret
    # user.client_secret = generate_client_secret()
    user.client_secret = str(uuid.uuid4())
    db.commit()

    return JSONResponse({
        "code": 1,
        "msg": "接口申请成功",
        "url": "/user/dashboard"
    })


@router.get("/vip")
def vip_page(request: Request, db: Session = Depends(get_db)):
    user_id = request.session.get("user_id")
    user = None
    if user_id:
        user = db.query(Users).filter(Users.user_id == user_id).first()

    if not user:
        return RedirectResponse("/user/login")

    vip_plans = ConfigData.get_vip_plans()

    # 将 user 传给模板
    return templates.TemplateResponse(
        "vip.html",
        {
            "request": request,
            "user": user,
            "vip_plans": vip_plans
        }
    )


@router.get("/logout")
def logout(request: Request):
    """
    用户安全退出
    """
    # 清除 session 中的用户信息
    request.session.pop("user", None)
    request.session.pop("user_id", None)

    # 重定向到首页
    return RedirectResponse("/", status_code=302)
